package com.zpf.dao.impl;

import com.zpf.dao.UserDao;
import com.zpf.pojo.User;
import com.zpf.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    //获取数据源
    //创建dbUtils工具
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDateSource());

    @Override
    public User findByUserName(String username) {

        String sql ="select * from tb_user where username=?";
        try {
            User user = queryRunner.query(sql, new BeanHandler<User>(User.class), username);
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addUser(User user) {
        String sql ="INSERT INTO `tb_user` (\n" +
                "  `username`,\n" +
                "  `password`,\n" +
                "  `email`,\n" +
                "  `gender`,\n" +
                "  `status`,\n" +
                "  `role`,\n" +
                "  `code`\n" +
                ") \n" +
                "VALUES\n" +
                "  (\n" +
                "    ?,\n" +
                "    ?,\n" +
                "    ?,\n" +
                "    ?,\n" +
                "    ?,\n" +
                "    ?,\n" +
                "   ?\n" +
                "  ) ;\n";
        try {
            int count = queryRunner.update(sql, user.getUsername(), user.getPassword(), user.getEmail(), user.getGender(), user.getStatus(), user.getRole(), user.getCode());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  0;
    }
}
